#include "bee_api.h"

/* GPIO 5 */
#define PWM_0_OUT_IO_NUM 5

// PWM period 1000us(1Khz), same as depth
#define PWM_PERIOD (1000) //4k /* 频率 */
//static const char *TAG = "pwm_example";

// pwm pin number
const uint32_t pin_num[1] = {
    PWM_0_OUT_IO_NUM,
};

// duties table, real_duty = duties[x]/PERIOD/* 响度 */
uint32_t duties[1] = {
    30};

// phase table, delay = (phase[x]/360)*PERIOD
int16_t phase[1] = {
    45};

void button_bee(void);
void musicPlay(void);
void buzzerInit(void);
void buzzerQuiet(void);
static void alarm_tone(void);
Tone tone = {
    .press = 0,
    .button_tone = button_bee,
    .alarm_tone = alarm_tone,
    .music_play = musicPlay,
    .on = buzzerInit,
    .quiet = buzzerQuiet,
};


void buzzerInit(void)
{
    //pwm_init(370, duties, 1, pin_num);
    pwm_init(500, duties, 1, pin_num);
}
/* 静音 */
void buzzerQuiet(void)
{
    pwm_deinit();
}



//蜂鸣器发出指定频率的声音
//usFreq是发声频率，取值 (系统时钟/65536)+1 ～ 20000，单位：Hz
static void buzzerSound(unsigned short usFreq)
{
    // GPIO_InitTypeDef  GPIO_InitStructure;
    //unsigned long ulVal;
    if ((usFreq <= 1000000 / 65536UL) || (usFreq > 50000))
    {
        buzzerQuiet(); // 蜂鸣器静音
    }
    else
    {
        pwm_init((1000000 / usFreq), duties, 1, pin_num);
        pwm_start();
    }
}


os_timer_t key_bee_50ms;
void key_bee_50ms_cb(void *args)
{
    pwm_stop(0x01);
    
}

static void alarm_tone(void)
{
    uint8_t i = 0;
    for(i = 0; i < 4;i++)
    {
        pwm_start();
        delay_ms(50);
        pwm_stop(0x01);
        delay_ms(50);
    }
  
}

void button_bee(void)
{
    if(tone.press && Dsystem.sys_voice_ctrl){
        pwm_start();
        delay_ms(50);
        pwm_stop(0x01);
        //os_timer_disarm(&key_bee_50ms);
        //os_timer_setfn(&key_bee_50ms, (os_timer_func_t *)key_bee_50ms_cb, 0);
        //os_timer_arm(&key_bee_50ms, 50, 0);
        tone.press = 0;
    }
}

// 演奏乐曲
// 此为延时函数控
void musicPlay(void)
{
    #if 0
    uint8_t i = 0;
    while (1)
    {
        if (MyScore[i].mTime == 0)
            break;
        buzzerSound(MyScore[i].mName);
        delay_ms(MyScore[i].mTime);
        i++;
        buzzerQuiet(); // 蜂鸣器静音
        delay_ms(1);   // 10 ms
    }
    #endif
}

